package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DeleteTemporaryDirectoryWithShutdownHook {
	public static void main(String[] args) {
		final Path basedir = FileSystems.getDefault().getPath("E:/Copy/");
		final String tmp_dir_prefix = "test_";

		try {
			Path tmp_dir = Files.createTempDirectory(basedir, tmp_dir_prefix);
			Runtime.getRuntime().addShutdownHook(new Thread() {
				@Override
				public void run() {
					System.out.println("删除临时文件夹 ...");
					try (DirectoryStream<Path> ds = Files.newDirectoryStream(tmp_dir)) {
						for (Path file : ds) {
							Files.delete(file);
						}
						Files.delete(tmp_dir);
					} catch (IOException e) {
						System.err.println(e);
					}
					System.out.println("Shutdown-hook 执行完毕...");
				}
			});
			Thread.sleep(1000);
		} catch (IOException | InterruptedException e) {
			System.err.println(e);
		}
	}
}
